package com.hlingsoft.cms.action;


import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.cms.constant.TagsConstant;
import com.hlingsoft.cms.dao.ImageDao;
import com.hlingsoft.cms.dao.TagsDao;
import com.hlingsoft.cms.entity.Image;
import com.hlingsoft.cms.entity.Tags;
import com.hlingsoft.cms.util.Common;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by selbylei on 2015/6/2.
 */

@Controller
@RequestMapping("tags")
public class TagsAction extends BaseAction {

    @Autowired
    private TagsDao tagsDao;

    @Autowired
    private ImageDao imageDao;


    /**
     * 添加贴纸
     *
     * @param appUserId
     * @param request
     * @return
     */
    @RequestMapping(value = "/add.json")
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "appUserId",required = false) Integer appUserId,
            @RequestParam(value = "type") int type, //1.用户贴纸 2.系统贴纸 3.明星贴纸

            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Date now = new Date();
            Tags tags = new Tags();
            if (type==1){
               tags.setAppUserId(appUserId);
            }else {
                tags.setAppUserId(0);
            }

            MultipartFile file = null;
            file = ((MultipartHttpServletRequest) request).getFile("file");
            String fileName = file.getOriginalFilename();
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = simpleFormat.format(new Date());
            putObject(dateString, fileName, file.getInputStream(),
                    file.getSize());
            String imagePath = "http://icake.oss-cn-hangzhou.aliyuncs.com/tags/" + dateString + "/" + fileName;

            tags.setType(type);
            tags.setPath(imagePath);
            tags.setCreateTime(now);
            tags.setUpdateTime(now);
            tagsDao.addTags(tags);

            CommonsMultipartFile cf= (CommonsMultipartFile)file;
            DiskFileItem fi = (DiskFileItem)cf.getFileItem();
            File f = fi.getStoreLocation();
            BufferedImage sourceImg = ImageIO.read(new FileInputStream(f));


            Image image = new Image();
            image.setWidth(sourceImg.getWidth());
            image.setHeight(sourceImg.getHeight());
            image.setAppUserId(appUserId);
            image.setPath(imagePath);
            image.setType(3);
            image.setCreateTime(now);
            image.setTokeTime(now);
            image.setUpdateTime(now);
            image.setTagsId(tags.getId());
            imageDao.addImages(image);

            resultMap.put("tags",tags);
            resultMap.put("result",true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 获取贴纸
     *
     * @param appUserId
     * @param request
     * @return
     */
    @RequestMapping(value = "/list.json")
    @ResponseBody
    public Map<String, Object> list(
            @RequestParam(value = "appUserId",required = false) Integer appUserId,
            @RequestParam(value = "type") int type,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (appUserId==null){
                appUserId=0;
            }

            List<Tags> tagsList = tagsDao.getTags(appUserId,type);

            resultMap.put("tagsList",tagsList);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 删除贴纸
     * @param tagsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public Map<String, Object> delete(
            @RequestParam(value = "tagsId") Integer tagsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            tagsDao.deleteTags(tagsId);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("icake", "tags/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }
}
